<?php

namespace app\manystore\controller;

use app\common\controller\ManystoreBase;
use app\common\model\Goodorder;
use app\common\model\Ordersessions;
use app\common\model\User;
use think\Cache;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Proxyorder extends ManystoreBase
{

    /**
     * Sessions模型对象
     * @var \app\manystore\model\Sessions
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Sessions;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

        }
        return $this->view->fetch();
    }

    //  商品列表
    public function products(){
       // $list=\app\manystore\model\Products::where('shop_id','=',SHOP_ID)->select();

        $products = Db::table('fa_products')
            ->alias('p')
            ->join('fa_product_specs s', 'p.id = s.product_id', 'LEFT') // 左连接
            ->where('p.status', '1') // 只查询上架商品
            ->where('p.shop_id', SHOP_ID)
            ->field('
                p.id as product_id,
                p.shop_id,
                p.category_id,
                p.name,
                p.image,
                p.description,
                COALESCE(s.price, p.price) as price, 
                COALESCE(s.sales, p.sales) as sales,   
                COALESCE(s.stock, p.stock) as stock,  
                COALESCE(s.spec_name, "") as spec_name,
                p.status,
                s.id as spec_id  
            ')
            ->order('p.weigh', 'asc') // 按照权重排序
            ->select();

        return json($products);
    }

    //下单
    public function add_good_order(){

        $data = input('post.');
        $cacheKey = 'submit_' . md5(serialize($data));
        // 检查缓存中是否存在该键名
        if (Cache::has($cacheKey)) {
            return json(['code'=>0,'messgin'=>'您点的太快了']);
        }
        Cache::set($cacheKey, true, 3);
        db::startTrans();
        if($data['lampCode']==null||$data['lampCode']==""){
            $Ordersessions= Ordersessions::create([
                'shop_id'=>SHOP_ID,
                'type'=>1,
            ]);
        }else{
          $light=  \app\manystore\model\Lights::where('shop_id',SHOP_ID)->where('code','=',$data['lampCode'])->find();
            if(!$light){
                return json(['code'=>0,'messgin'=>'灯码不存在']);
            }
            $occupants= \app\manystore\model\Occupants::where('shop_id',SHOP_ID)->where('lights_id',$light['id'])->where('status',0)->find();
            if(!$occupants){
                return json(['code'=>0,'messgin'=>'当前灯码订单未开始或已结束']);
            }
            $Ordersessions= Ordersessions::create([
                'shop_id'=>SHOP_ID,
                'occupants_id'=>$occupants['id'],
                'user_id'=>$occupants['user_id'],
            ]);
        }
        $array=$data['cartItems'];
        foreach ($array as $item){
            $Products=\app\common\model\Products::where('id',$item['product_id'])->find();
            //多规格
            $has_specs=0;
            $Spece='';
            if($item['spec_id']!=null&&$item['spec_id']!=''){
                $Spece= \app\manystore\model\Spece::where('id',$item['spec_id'])->find();
                $has_specs=1;
            }
            $price=$Spece?$Spece['price']:$Products['price'];
            Goodorder::create([
                'occupants_id'=>$data['lampCode']==null?null:$occupants['id'],
                'order_session_id'=>$Ordersessions->id,
                'goodimage'=>$Products['image'],
                'goodname'=>$Products['name'],
                'price'=>$price,
                'goodid'=>$item['product_id'],
                'spec'=>$has_specs==1?$Spece['spec_name']:'常规',
                'num'=>$item['num'],
                'total'=>$item['num']*$price
            ]);
            if($has_specs==0){
                $result= \app\common\model\Products::where('id',$item['product_id'])->where('stock','=',$Products['stock'])->where('stock','egt',$item['num'])->setDec('stock',$item['num']);
            }else{
                $result=  \app\manystore\model\Spece::where('id',$item['spec_id'])->where('stock','=',$Spece['stock'])->where('stock','egt',$item['num'])->setDec('stock',$item['num']);
            }
            if($result==0){
                db::rollback();
                return json(['code'=>0,'messgin'=>'商品库存不足']);
            }
        }
        db::commit();
        return json(['code'=>1,'messgin'=>'下单成功']);
    }


}
